//
//  LJEmoctionViewController.swift
//  LJ表情键盘
//
//  Created by Raymond on 15/12/28.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit

class LJEmoctionViewController: UIViewController {
    
    /// 表情包数组
    var emoctionPackages = LJEmoctionPackage.packages
    
    /// 重用表示
    private let reuseIdentifier = "ReuseIdentifier"
    
    /// 起始tag值
    let baseTag = 1000
    
    /// 选中的按钮
    var selectedButton: UIButton?
    
    /// 输入的textview
    weak var textView: UITextView?
    
    init(textView: UITextView){
        self.textView = textView
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor = UIColor.whiteColor()
        prepareUI()
//        print(emoctionPackages)
    }
    
    func prepareUI() {
        view.addSubview(toolBar)
        view.addSubview(emoctionView)
        
//        emoctionView.backgroundColor = UIColor.blueColor()
        
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        emoctionView.translatesAutoresizingMaskIntoConstraints = false
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ev]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ev" : emoctionView]))
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : toolBar]))
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ev]-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ev" : emoctionView, "tb" : toolBar]))
        setupToolBar()
        setupEmoctionView()
        
    }
    
    private func setupToolBar() {
        var items = [UIBarButtonItem]()
        var index = 0
        for package in emoctionPackages! {
            let name = package.group_name_cn
            
            let button = UIButton()
            button.setTitle(name, forState: UIControlState.Normal)
            button.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Highlighted)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
            button.sizeToFit()
            
            // 添加按钮点击事件
            button.addTarget(self, action: "toolBarDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            button.tag = index + baseTag
            
            // 默认选中第0组
            if index == 0 {
                switchSelectedButton(button)
            }
            
            let item = UIBarButtonItem(customView: button)
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
            index++
        }
        items.removeLast()
        toolBar.items = items
    }
    
    private func setupEmoctionView() {
        // 注册cell
        emoctionView.registerClass(LJEmoctionCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        // 设置背景色
        emoctionView.backgroundColor = UIColor(white: 0.88, alpha: 1)
        
        // 指定数据源
        emoctionView.dataSource = self
        // 指定代理
        emoctionView.delegate = self
    }
    
    // MARK: - 工具条点击方法
    @objc func toolBarDidClick(button: UIButton) {
        // 滚动到相应组
        emoctionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: button.tag - baseTag), atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        // 切换按钮的选中状态
        switchSelectedButton(button)
    }
    
    private func switchSelectedButton(button: UIButton) {
        selectedButton?.selected = false
        button.selected = true
        selectedButton = button
    }

    // MARK: - 懒加载
    /// 工具条
    private lazy var toolBar: UIToolbar = UIToolbar()
    /// 表情栏
    private lazy var emoctionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: LJCollectionViewFlowLayout())
}

// MARK: - 扩展
extension LJEmoctionViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return emoctionPackages?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let package = emoctionPackages![section]
        return package.emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! LJEmoctionCell
//        cell.backgroundColor = UIColor.randomColor()
        
        let package = emoctionPackages![indexPath.section]
        let emoction = package.emoticons[indexPath.item]
        
        cell.emoction = emoction
        return cell
        
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 获取当前选中的组
        let package = emoctionPackages![indexPath.section]
        // 获取对应的表情
        let emoction = package.emoticons[indexPath.item]
        // 添加到textview
        textView!.insertEmoction(emoction)
        // 点击最近表情不参与排序
        if indexPath.section != 0 {
            LJEmoctionPackage.addFavorateEmoction(emoction)
        }
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 获取正在显示的index
        let indexPaths = emoctionView.indexPathsForVisibleItems()
        // 获取中间的index
        let indexPath = indexPaths[10]
        // 获取正在显示的组
        let section = indexPath.section
        // 获得对应tag值的按钮
        let button = toolBar.viewWithTag(section + baseTag) as! UIButton
        // 切换按钮
        switchSelectedButton(button)
    }
}

// MARK: - 自定义流水布局
class LJCollectionViewFlowLayout: UICollectionViewFlowLayout {
    // 覆盖父类的布局方法
    override func prepareLayout() {
        super.prepareLayout()
        
        // 设置item大小
        let itemWidth = collectionView!.frame.width / 7
        let itemHeight = collectionView!.frame.height / 3
        self.itemSize = CGSize(width: itemWidth, height: itemHeight)
        
        // 设置间距
        self.minimumInteritemSpacing = 0
        self.minimumLineSpacing = 0
        
        // 设置滚动方向
        self.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        // 分页
        collectionView!.pagingEnabled = true
        // 弹簧
        collectionView!.bounces = false
        // 滚动条
        collectionView!.showsHorizontalScrollIndicator = false
        
    }
}
